package com.joke.util;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

public class HttpClientGet/* extends HttpClientAdapter*/ {
	
	private static PoolingHttpClientConnectionManager connMgr;  
    private static RequestConfig requestConfig;  
    private static final int MAX_TIMEOUT = 600000;  
  
    static {  
        // 设置连接池  
        connMgr = new PoolingHttpClientConnectionManager();  
        // 设置连接池大小  
        connMgr.setMaxTotal(100);  
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());  
  
        RequestConfig.Builder configBuilder = RequestConfig.custom();  
        // 设置连接超时  
        configBuilder.setConnectTimeout(MAX_TIMEOUT);  
        // 设置读取超时  
        configBuilder.setSocketTimeout(MAX_TIMEOUT);  
        // 设置从连接池获取连接实例的超时  
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);  
        // 在提交请求之前 测试连接是否可用  
        configBuilder.setStaleConnectionCheckEnabled(true);  
        requestConfig = configBuilder.build();  
    }
	
//    private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000)
//            .setConnectionRequestTimeout(15000).build();
	// 创建默认的httpClient实例

    private static CloseableHttpClient  httpClient = HttpClients.createDefault();
    private static Map<String, String> header = new HashMap<>();
    
    // 单例模式
//    private HttpClientGet instance = null;
//    private HttpClientGet() {
//    	
//    }
/*    public static HttpClientGet getInstance() {
    	if (instance == null) {
    		instance = new HttpClientGet();
    	}
    	return instance;
    }*/
    
    public static void setHeader(Map<String, String> headers) {
    	headers.put("Accept", "text/html, application/xhtml+xml, image/jxr, */*");
    	headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
    	headers.put("Accept-Language", "zh-CN");
    	headers.put("Connection", "Keep-Alive");
    	headers.put("Content-Type", "text/html; charset=UTF-8");
		headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36");
		header = headers;
    }
    
	public static void  creatProxyHttpClient(String hostName, int port) {
		// 使用代理服务器
		httpClient = HttpClients.custom().setProxy(new HttpHost(hostName, port)).build();
	}

	public static void createDefaultHttpClient() {
		// 创建默认的httpClient实例
		httpClient = HttpClients.createDefault();
	}
	
    /**
     * 发送Get请求 http://
     * @param httpPost
     * @return
     */
//	@Override
    public static String sendHttpGet(String httpUrl) {
		HttpGet httpGet = new HttpGet(httpUrl);
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            httpGet.setConfig(requestConfig);
            for (String key : header.keySet()) {
            	httpGet.addHeader(key, header.get(key));	
			}
            response = httpClient.execute(httpGet);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return responseContent;
    }

    /**
     * 发送Get请求 https://
     * @param httpPost
     * @return
     */
//	@Override
	public static String sendHttpsGet(String httpsUrl) {
		HttpGet httpGet = new HttpGet(httpsUrl);
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader
                    .load(new URL(httpGet.getURI().toString()));
            DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
            httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
            httpGet.setConfig(requestConfig);
            
            response = httpClient.execute(httpGet);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return responseContent;
    }
}
